/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package samples.tasks.io;

import taskgraph.channels.CharChannel;
import taskgraph.ports.CharInputPort;
import taskgraph.tasks.Graph;
import taskgraph.tasks.PrimitiveTask;
import taskgraph.tasks.Task.Wait;
import taskgraph.tasks.io.ReadTextFile;


/**
 * Prints the first 10 lines of the input file.
 * It demonstrates an in-line primitive task, for
 * code that is unlikely to be reused.
 *  
 * @author Armando Blancas
 */
public class Head {
	
	/**
     * Creates a graph that prints the start of the input text file.
     * <p><pre>
     * [ReadText] --ch1--> [Head]
     * </pre>
     * This class (Head) uses an anonymous class to process the lines
     * read from the input file. This saves the effort of creating
     * a special task just for this case. 
	 */
	public static final void main(String[] args) {
		if (args.length == 0) {
			System.out.println("Usage: java samples.tasks.text.Head <file>");
			System.exit(1);
		}
		
		try {
			Graph graph = new Graph();
			CharChannel channel = new CharChannel();
			final CharInputPort input = channel.getInputPort();
			
			graph.add(new ReadTextFile(channel.getOutputPort(), args[0]));
			
			// Custom, in-line task for a particular purpose.
			graph.add(new PrimitiveTask() {
				@Override
				public void run() {
					try {
						int count = 0;
						String s = input.readLine();
						while (s != null && count++ < 10) {
							System.out.println(s);
							s = input.readLine();
						}
					} catch (Throwable t) {
						System.err.printf("Error:\n%s\n", t.getMessage());
					} finally {
						input.close();						
					}
				}				
			});
			
			graph.execute(Wait.NO_WAIT);
		} catch (InterruptedException e) {
			System.err.printf("Interrupted:\n%s\n", e.getMessage());
		}
	}

}
